package com.github.shiqiyue.app.config.security.sapi;


import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.utils.IpUtils;
import com.github.shiqiyue.app.common.utils.ResponseUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/***
 * 后台用户登录成功处理
 * @author wenyao.wu
 * @date 2019/7/11
 */
public class SapiAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    /***
     *  useragent存放到session中的key
     */
    private String sessionKeyUserAgent;

    /***
     * ip存放到session的key
     */
    private String sessionKeyIp;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 登录成功后，将user-agent和ip地址设置到session中
        HttpSession httpSession = httpServletRequest.getSession();
        httpSession.setAttribute(sessionKeyUserAgent, httpServletRequest.getHeader(HttpHeaders.USER_AGENT));
        httpSession.setAttribute(sessionKeyIp, IpUtils.getIpAddr(httpServletRequest));
        //返回token
        Map<String, Object> resBody = new HashMap<>(1);
        resBody.put("token", httpServletRequest.getSession().getId());
        ResponseUtils.populateResponse(ResponseEntity.ok(Result.success(resBody)), httpServletResponse);
        
    }

    public void setSessionKeyUserAgent(String sessionKeyUserAgent) {
        this.sessionKeyUserAgent = sessionKeyUserAgent;
    }

    public void setSessionKeyIp(String sessionKeyIp) {
        this.sessionKeyIp = sessionKeyIp;
    }
}
